package payrechargelogic

import (
	"context"
	"net/http"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/xerrors"

	model "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/recharge"
	withdrawModel "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/model/withdraw"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/recharge"
	recharge2 "gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/service/recharge"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/utils"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"
	"gitee.com/liuxuezhan/ar-platform/base-common/pkg/xcode"
	baseRpc "gitee.com/liuxuezhan/ar-platform/base-common/rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RechargeCreateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRechargeCreateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RechargeCreateLogic {
	return &RechargeCreateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// RechargeCreate Recharge 充值订单创建
func (l *RechargeCreateLogic) RechargeCreate(in *rpc.RechargeCreateRequest) (*rpc.RechargeCreateResponse, error) {
	// 制作订单号
	orderNo := utils.GenerateOrderId("RC")

	if err := l.validateCreate(in); err != nil {
		return nil, err
	}
	rate := withdrawModel.NewVirtualDicModel(l.ctx, l.svcCtx).GetRate(in.Coin)
	if rate == 0 {
		return nil, xerrors.ErrRateCANTNUll
	}
	// 制作数据
	createOrder := &recharge.RechargeOrder{
		UserID:    in.UserId,
		OrderNo:   orderNo,
		Type:      in.Type,
		ChannelID: in.ChannelId,
		// bet豆
		Amount: in.Amount * rate, // 乘以汇率
		Status: model.PENDING,
		Domain: baseRpc.GetOriginHost(l.ctx),

		ActualAmount: in.Amount,
		CustomerInfo: recharge2.NewCreateService(l.ctx, l.svcCtx).
			BuildCustomerInfoByRechargeCreate(in).
			String(),
		BankUpi: recharge2.NewCreateService(l.ctx, l.svcCtx).
			BuildBankUPIByRechargeCreate(in).DbString(),
		Facebook: *in.Fackbook,
		Coin:     in.Coin,
	}
	// 创建订单
	err := model.NewRechargeOrderModel(l.ctx, l.svcCtx.Db).CreateRechargeOrder(createOrder)
	if err != nil {
		return nil, err
	}
	return &rpc.RechargeCreateResponse{
		OrderNo: createOrder.OrderNo,
	}, nil
}

func (l *RechargeCreateLogic) validateCreate(in *rpc.RechargeCreateRequest) error {
	var res error

	service := recharge2.NewCreateService(l.ctx, l.svcCtx)
	typeInfo := service.GetRechargeType(int64(in.Type))
	if typeInfo.ID == 0 {
		return xcode.NewRpc(http.StatusBadRequest, "Type not exists.")
	}

	switch int(typeInfo.ID) {
	case recharge.InternalLocalUsdt:
		if in.TenantId == 0 {
			return xcode.NewRpc(http.StatusBadRequest, "Local-Usdt tenant_id must. ")
		}
		if in.UserInfo.UsdtAddress == "" {
			return xcode.NewRpc(http.StatusBadRequest, "Local-Usdt user_address must. ")
		}
	default:
	}

	return res
}
